/*
 * MultiButton库高级示例
 * 本示例演示了高级功能和动态按键管理
 */

#include "multi_button.h"
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>

#define MAX_BUTTONS 4

// 按键实例
static Button buttons[MAX_BUTTONS];
static volatile int running = 1;
static int button_states[MAX_BUTTONS] = {0};

// 配置参数
static int demo_mode = 1;      // 是否演示模式
static int verbose_mode = 0;   // 是否详细输出

// 信号处理函数，用于优雅退出
void signal_handler(int sig)
{
    if (sig == SIGINT) {
        printf("\n🛑 收到SIGINT信号，正在清理...\n");
        running = 0;
    }
}

// 硬件抽象层函数，读取按键GPIO状态
uint8_t read_button_gpio(uint8_t button_id)
{
    if (button_id > 0 && button_id <= MAX_BUTTONS) {
        return button_states[button_id - 1];
    }
    return 0;
}

// 通用事件处理函数，显示按键信息
void generic_event_handler(Button* btn, const char* event_name)
{
    if (verbose_mode) {
        printf("🔘 按键%d: %s (重复: %d, 按下: %s)\n", 
               btn->button_id, 
               event_name,
               button_get_repeat_count(btn),
               button_is_pressed(btn) ? "是" : "否");
    } else {
        printf("🔘 按键%d: %s\n", btn->button_id, event_name);
    }
}

// 事件处理函数
void on_press_down(Button* btn) { generic_event_handler(btn, "按下"); }
void on_press_up(Button* btn) { generic_event_handler(btn, "松开"); }
void on_single_click(Button* btn) { generic_event_handler(btn, "单击"); }
void on_double_click(Button* btn) { generic_event_handler(btn, "双击"); }
void on_long_press_start(Button* btn) { generic_event_handler(btn, "长按开始"); }
void on_long_press_hold(Button* btn) { generic_event_handler(btn, "长按保持"); }
void on_press_repeat(Button* btn) { generic_event_handler(btn, "连发"); }

// 配置按键的特殊处理函数
void on_config_button_click(Button* btn)
{
    static int config_state = 0;
    
    printf("⚙️ 配置按键%d被点击！\n", btn->button_id);
    
    switch (config_state) {
        case 0:
            verbose_mode = !verbose_mode;
            printf("📝 详细模式: %s\n", verbose_mode ? "开启" : "关闭");
            break;
        case 1:
            demo_mode = !demo_mode;
            printf("🎭 演示模式: %s\n", demo_mode ? "开启" : "关闭");
            break;
        case 2:
            printf("🔄 重置所有按键...\n");
            for (int i = 0; i < MAX_BUTTONS; i++) {
                button_reset(&buttons[i]);
            }
            break;
        case 3:
            printf("👋 停止演示...\n");
            running = 0;
            break;
    }
    
    config_state = (config_state + 1) % 4;
}

// 初始化单个按键及其事件
void init_button(int index, uint8_t button_id, int enable_all_events)
{
    button_init(&buttons[index], read_button_gpio, 1, button_id);
    
    if (enable_all_events) {
        button_attach(&buttons[index], BTN_PRESS_DOWN, on_press_down);
        button_attach(&buttons[index], BTN_PRESS_UP, on_press_up);
        button_attach(&buttons[index], BTN_SINGLE_CLICK, on_single_click);
        button_attach(&buttons[index], BTN_DOUBLE_CLICK, on_double_click);
        button_attach(&buttons[index], BTN_LONG_PRESS_START, on_long_press_start);
        button_attach(&buttons[index], BTN_LONG_PRESS_HOLD, on_long_press_hold);
        button_attach(&buttons[index], BTN_PRESS_REPEAT, on_press_repeat);
    } else {
        // 只绑定基础事件
        button_attach(&buttons[index], BTN_SINGLE_CLICK, on_single_click);
        button_attach(&buttons[index], BTN_DOUBLE_CLICK, on_double_click);
        button_attach(&buttons[index], BTN_LONG_PRESS_START, on_long_press_start);
    }
    
    button_start(&buttons[index]);
}

// 初始化所有按键
void buttons_init(void)
{
    printf("🔧 初始化%d个按键...\n", MAX_BUTTONS);
    
    // 按键1：全功能
    init_button(0, 1, 1);
    printf("  ✅ 按键1: 全功能\n");
    
    // 按键2：基础事件
    init_button(1, 2, 0);
    printf("  ✅ 按键2: 基础事件\n");
    
    // 按键3：配置按键，绑定特殊处理
    init_button(2, 3, 0);
    button_detach(&buttons[2], BTN_SINGLE_CLICK);
    button_attach(&buttons[2], BTN_SINGLE_CLICK, on_config_button_click);
    printf("  ✅ 按键3: 配置按键\n");
    
    // 按键4：动态配置演示
    init_button(3, 4, 0);
    printf("  ✅ 按键4: 动态配置演示\n");
    
    printf("🎯 所有按键初始化完成！\n\n");
}

// 模拟按键按下
void simulate_button_press(int button_id, int duration_ms)
{
    if (button_id < 1 || button_id > MAX_BUTTONS) return;
    
    if (verbose_mode) {
        printf("📱 模拟按键%d按下 (%d ms)\n", button_id, duration_ms);
    }
    
    button_states[button_id - 1] = 1;
    
    for (int i = 0; i < duration_ms / 5; i++) {
        button_ticks();
        usleep(5000);
    }
    
    button_states[button_id - 1] = 0;
    
    for (int i = 0; i < 10; i++) {
        button_ticks();
        usleep(5000);
    }
}

// 动态配置演示
void dynamic_config_demo(void)
{
    printf("\n🔄 动态配置演示\n");
    printf("=====================================\n");
    
    // 初始时按键4只有最少的事件
    printf("1. 测试按键4（最少事件）...\n");
    simulate_button_press(4, 100);
    
    usleep(300000);
    
    // 动态添加更多事件
    printf("2. 动态添加更多事件到按键4...\n");
    button_attach(&buttons[3], BTN_PRESS_DOWN, on_press_down);
    button_attach(&buttons[3], BTN_PRESS_UP, on_press_up);
    button_attach(&buttons[3], BTN_PRESS_REPEAT, on_press_repeat);
    
    printf("3. 测试按键4（全部事件）...\n");
    simulate_button_press(4, 100);
    
    usleep(300000);
    
    // 移除部分事件
    printf("4. 移除按下/松开事件...\n");
    button_detach(&buttons[3], BTN_PRESS_DOWN);
    button_detach(&buttons[3], BTN_PRESS_UP);
    
    printf("5. 测试按键4（部分事件）...\n");
    simulate_button_press(4, 100);
}

// 交互式演示流程
void run_demo_sequence(void)
{
    printf("\n🎭 交互式演示流程\n");
    printf("=====================================\n");
    
    printf("演示1：所有按键单击\n");
    for (int i = 1; i <= MAX_BUTTONS; i++) {
        simulate_button_press(i, 100);
        usleep(200000);
    }
    
    printf("\n演示2：双击模式\n");
    simulate_button_press(1, 80);
    usleep(50000);
    simulate_button_press(1, 80);
    usleep(500000);
    
    printf("\n演示3：长按演示\n");
    simulate_button_press(2, 1200);
    usleep(300000);
    
    printf("\n演示4：快速连按\n");
    for (int i = 0; i < 4; i++) {
        simulate_button_press(1, 60);
        usleep(70000);
    }
    usleep(500000);
    
    printf("\n演示5：配置按键测试\n");
    for (int i = 0; i < 3; i++) {
        simulate_button_press(3, 100);
        usleep(200000);
    }
}

// 打印按键状态
void print_button_status(void)
{
    printf("\n📊 按键状态报告\n");
    printf("========================\n");
    for (int i = 0; i < MAX_BUTTONS; i++) {
        printf("按键%d: ", buttons[i].button_id);
        printf("状态=%d, ", button_is_pressed(&buttons[i]));
        printf("重复=%d, ", button_get_repeat_count(&buttons[i]));
        ButtonEvent event = button_get_event(&buttons[i]);
        printf("事件=%d\n", event);
    }
}

// 主函数
int main(int argc, char* argv[])
{
    printf("🚀 MultiButton库高级示例\n");
    printf("==========================================\n");
    
    // 解析命令行参数
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--verbose") == 0) {
            verbose_mode = 1;
        } else if (strcmp(argv[i], "-q") == 0 || strcmp(argv[i], "--quiet") == 0) {
            demo_mode = 0;
        }
    }
    
    printf("配置: 演示=%s, 详细=%s\n\n", 
           demo_mode ? "开启" : "关闭", 
           verbose_mode ? "开启" : "关闭");
    
    // 设置信号处理
    signal(SIGINT, signal_handler);
    
    // 初始化按键
    buttons_init();
    
    if (demo_mode) {
        // 运行演示流程
        run_demo_sequence();
        
        // 动态配置演示
        dynamic_config_demo();
        
        // 打印最终状态
        print_button_status();
        
        printf("\n✅ 高级演示已完成！\n");
        printf("💡 按Ctrl+C退出，或使用--quiet参数进入手动测试\n");
    } else {
        printf("🎮 手动测试模式 - 按键已就绪\n");
        printf("💡 按Ctrl+C退出\n");
    }
    
    // 持续运行直到被中断
    while (running) {
        button_ticks();
        usleep(5000); // 5ms周期
    }
    
    // 清理
    printf("\n🧹 正在清理...\n");
    for (int i = 0; i < MAX_BUTTONS; i++) {
        button_stop(&buttons[i]);
    }
    
    printf("👋 高级示例结束！\n");
    return 0;
}

/*
 * 构建与运行说明:
 * 
 * 构建:
 * make advanced_example
 * 
 * 演示运行:
 * ./build/bin/advanced_example
 * 
 * 详细输出运行:
 * ./build/bin/advanced_example -v
 * 
 * 静默模式（手动测试）:
 * ./build/bin/advanced_example -q
 */ 